package com.unicom.projt.fee;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.unicom.projt.Home;
import com.unicom.projt.InputPhoneNumberPage;
import com.unicom.projt.Main;
import com.unicom.projt.R;
import com.unicom.projt.util.*;
import com.unionpay.upomp.bypay.util.UPOMP;
import com.unionpay.upomp.bypay.util.Utils;

import java.text.DecimalFormat;

/**
 * Created by IntelliJ IDEA.
 * User: Lee
 * Date: 11-12-6
 * Time: 上午9:43
 */
public class PaymentConfirmPage extends Activity implements View.OnClickListener {
    private TextView mAmount;
    private TextView mPhoneNumber;
    private double amount = 0;
    private String phoneNumber;
    private String orderId;
    private String payPkg;
    private String cardNo;
    private String cardPwd;
    private boolean isIvrPay = false;

    private String bankName;
    private String cardNumber;

    public static final String MY_PKG = "com.unicom.projt";
    public static final String PLUGIN_PKG_PAYMENT = "com.unionpay.upomp.bypay.paymain";

    private boolean isFirst = false;

    private ProgressDialog mDialog;
    private static final int DIALOG_PROGRESS = 12;

    private PaymentConfirmController mPaymentConfirmController;

    private Button mSJBtn;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.payment_confirm);
        ((TextView)this.findViewById(R.id.payment_confirm_number_txt)).setText(UserHolder.phoneNumber);

        mSJBtn =(Button) this.findViewById(R.id.payment_confirm_sj_btn);
        mSJBtn.setOnClickListener(this);

        mPaymentConfirmController= new PaymentConfirmController(this);
        Bundle extras = getIntent().getExtras();

//        isIvrPay = extras.getBoolean("isIvrPay");
        isIvrPay = UserHolder.isBindUser;
        amount = extras.getDouble("amount");
        phoneNumber = extras.getString("phoneNumber");
        orderId = extras.getString("orderId");
        payPkg = extras.getString("payPkg");
        if (isIvrPay) { //绑定用户
            bankName = UserHolder.bankName;
            cardNumber = UserHolder.cardNumber;
        }else{
            mSJBtn.setVisibility(View.GONE);
        }

        mAmount = (TextView) this.findViewById(R.id.payment_confirm_amount);
        mAmount.setText(new DecimalFormat("###,###,###.##").format(amount) + "元");
        mPhoneNumber = (TextView) this.findViewById(R.id.payment_confirm_phone_number);
        mPhoneNumber.setText(phoneNumber);

        this.findViewById(R.id.payment_confirm_confirm_btn).setOnClickListener(this);
        this.findViewById(R.id.payment_confirm_back_btn).setOnClickListener(this);
        this.findViewById(R.id.payment_confirm_logout_btn).setOnClickListener(this);
        isFirst = true;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.payment_confirm_back_btn:
                PageJumpUtils.jump(this, Home.class);
                this.finish();
                break;
            case R.id.payment_confirm_logout_btn:
                AlertDialogUtils.showYesNoDiaLog(this, "是否注销？", new AlertDialogUtils.Executor() {
                    @Override
                    public void execute() {
                        UserHolder.clean();
                        doLogout();
                    }
                });
                break;
            case R.id.payment_confirm_confirm_btn:
                doPay();
                break;
            case R.id.payment_confirm_sj_btn :
                gotoIvrInputPage();
                break;
        }

    }

    private void gotoIvrInputPage(){
        Intent intent = new Intent(this, IvrPasswordInputPage.class);
        intent.putExtra("amount", this.amount);
        intent.putExtra("phoneNumber", phoneNumber);
        intent.putExtra("bankName", bankName);
        intent.putExtra("cardNumber", cardNumber);
        this.startActivity(intent);
        this.finish();
    }

    private void doLogout(){
        Intent intent = new Intent(this, InputPhoneNumberPage.class);
        this.startActivity(intent);
        this.finish();
    }

    public void showPaymentSuccessPage() {
        Intent intent = new Intent(this, PaymentSuccessPage.class);
        intent.putExtra("amount", amount);
        intent.putExtra("phoneNumber", phoneNumber);
        intent.putExtra("orderId", orderId);
        this.startActivity(intent);
        this.finish();
    }

    private void doPay() {
         startUpompIntent(orderId, payPkg);
    }

    public void startUpompIntent(String orderId, String payPkg) {
        isFirst = false;
        Utils.setPackageName(MY_PKG);
        UPOMP.init();
        // 设置跳转到手机POS Intent
//        Intent intent = new Intent(this,com.unionpay.upomp.bypay.activity.PayMainActivity.class);
        Intent intent = new Intent(PLUGIN_PKG_PAYMENT);
        // 填充所携带的Bundle
        Bundle mBundle = new Bundle();
        // XML格式根据协议定义
        // 下面为示例代码，准确代码，请参考接口协议定义
//        String orderAmount = ((Double) (amount * 100)).intValue() + "";
//        String xml = XmlBuilder.getInstance().setMerchantOrderTime(DateUtils.formatOrderDateTime(new Date())).setMerchantOrderAmt("11000").buildDefaultXml();
//        mBundle.putString("xml",xml);
        mBundle.putString("xml", payPkg);
// 如果程序需要回调，请设置pkg
//        mBundle.putString("pkg", MY_PKG);
// 将bundle置于intent中
        // 将Bundle传递给intent
        intent.putExtras(mBundle);
        // 使用intent转到手机POS
        this.startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!isFirst) {
            this.hideProgressDialog();
            String result = UPOMP.getPayResult();
            if (result != null) {//成功
                String respCode=SimpleXmlParser.getElementsValue(result,"respCode").get(0);
                if("0000".equals(respCode)){
                    showPaymentSuccessPage();
                }else{
                  ToastUtils.showMessage(this, "支付失败,"+SimpleXmlParser.getElementsValue(result,"respDesc").get(0));
//                mPaymentConfirmController.queryUnicomPayOrderState(orderId);
//                showPaymentSuccessPage();
                }
            } else {
                ToastUtils.showMessage(this, "交易失败");
            }

        }
    }

    @Override
    public void onBackPressed() {
        PageJumpUtils.jump(this, Home.class);
        this.finish();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_SEARCH) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (UserHolder.phoneNumber.equals("")||UserHolder.phoneNumber==null) {
            this.finish();
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DIALOG_PROGRESS:
                mDialog = new ProgressDialog(this);
                mDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                mDialog.setMessage("正在处理，请等待......");
                mDialog.setCancelable(false);
                mDialog.setOnKeyListener(new DialogInterface.OnKeyListener(){
                    public boolean onKey(DialogInterface dialog, int keyCode,KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                            return true;
                        }
                        return false;
                    }
                });
                return mDialog;
            default:
                return null;
        }
    }

    public void hideProgressDialog() {
        if (mDialog != null) {
            removeDialog(DIALOG_PROGRESS);
        }
    }
}
